package cn.dgut.training.controller;


import cn.dgut.training.annotation.RequiresPermissionsDesc;
import cn.dgut.training.dto.AdminDTO;
import cn.dgut.training.entity.Admin;
import cn.dgut.training.service.impl.AdminServiceImpl;
import cn.dgut.training.util.ArrIntegerToString;
import cn.dgut.training.util.RegexUtil;
import cn.dgut.training.vo.CommonResponse;
import cn.hutool.core.date.DateTime;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.List;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Resource
    private AdminServiceImpl adminService;

    @RequiresPermissions("admin:admin:list")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "查询")
    @GetMapping("/list")
    public CommonResponse list(String username) {

        return CommonResponse.success( adminService.querySelective(username));
    }

    private CommonResponse validate(AdminDTO adminDTO) {
        String name = adminDTO.getUsername();
        if (StringUtils.isEmpty(name)) {
            return CommonResponse.fail(401, "参数不对");
        }
        if (!RegexUtil.isUsername(name)) {
            return CommonResponse.fail(601, "管理员名称不符合规定");
        }
        String password = adminDTO.getPassword();
        if (StringUtils.isEmpty(password) || password.length() < 6) {
            return CommonResponse.fail(602, "管理员密码长度不能小于6");
        }
        return null;
    }

    @RequiresPermissions("admin:admin:create")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "添加")
    @PostMapping("/create")
    public CommonResponse create(@RequestBody AdminDTO adminDTO) {
        Object error = validate(adminDTO);
        Admin admin=new Admin();
        if (error != null) {
            return CommonResponse.success(error);
        }

        String username = adminDTO.getUsername();
        List<Admin> adminList = adminService.findAdmin(username);
        if (adminList.size() > 0) {
            return CommonResponse.fail(622, "管理员已经存在");
        }

        String rawPassword = adminDTO.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(rawPassword);
        adminDTO.setPassword(encodedPassword);
        admin.setId(adminDTO.getId());
        admin.setUsername(adminDTO.getUsername());
        admin.setPassword(adminDTO.getPassword());
        admin.setAvatar(adminDTO.getAvatar());
        admin.setRoleIds(ArrIntegerToString.toString(adminDTO.getRoleIds()));
        adminService.add(admin);
        return CommonResponse.success(admin);
    }

    @RequiresPermissions("admin:admin:read")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "详情")
    @GetMapping("/read")
    public CommonResponse read(@NotNull Integer id) {
        Admin admin = adminService.getById(id);
        return CommonResponse.success(admin);
    }

    @RequiresPermissions("admin:admin:update")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "编辑")
    @PostMapping("/update")
    public CommonResponse update(@RequestBody AdminDTO adminDTO) {
        Object error = validate(adminDTO);
        Admin admin=new Admin();
        if (error != null) {
            return CommonResponse.success(error);
        }

        Long anotherAdminId = adminDTO.getId();
        if (anotherAdminId == null) {
            return CommonResponse.fail(401, "参数不对");
        }

        admin.setId(adminDTO.getId());
        admin.setUsername(adminDTO.getUsername());
        admin.setPassword(adminDTO.getPassword());
        admin.setAvatar(adminDTO.getAvatar());
        // 不允许管理员通过编辑接口修改密码
        admin.setPassword(null);
        admin.setUpdateTime(DateTime.now());

        admin.setRoleIds(ArrIntegerToString.toString(adminDTO.getRoleIds()));
        if (!adminService.updateById(admin)) {
            return CommonResponse.fail(505, "更新数据失败");
        }

        return CommonResponse.success(admin);
    }

    @RequiresPermissions("admin:admin:delete")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "删除")
    @PostMapping("/delete")
    public CommonResponse delete(@RequestBody AdminDTO adminDTO) {
        Long anotherAdminId = adminDTO.getId();
        if (anotherAdminId == null) {
            return CommonResponse.fail(401, "参数不对");
        }

        // 管理员不能删除自身账号
        Subject currentUser = SecurityUtils.getSubject();
        Admin currentAdmin = (Admin) currentUser.getPrincipal();
        if (currentAdmin.getId().equals(anotherAdminId)) {
            return CommonResponse.fail(603, "管理员不能删除自己账号");
        }

        adminService.removeById(anotherAdminId);
        return CommonResponse.message();
    }



}
